package com.island.practice.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.swing.*;

/**
 * Servlet implementation class DeleteRoleServlet
 */

public class DeleteRoleServlet extends AbstractServlet {
	
	private static final String SQL_SELECT_PERSON_ROLE_RELEATION = 
			"SELECT DISTINCT ROLE_ID FROM PERSON_ROLE_RELATION WHERE ROLE_ID = ?";
	
	/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    	
    	String roleID = request.getParameter("roleId");
    	
    	Connection connection = null;
    	PreparedStatement statement = null;
    	ResultSet roleResults = null;
    	    	
    	try {
			connection = this.getConnection();
	    	connection.setAutoCommit(false);
	    	
	    	//Check whether the roleId relates to persons.
	    	//If does, the roleId can't be deleted. The system will show a warning message.
	    	statement = connection.prepareStatement(SQL_SELECT_PERSON_ROLE_RELEATION);
    		statement.setString(1, roleID);
    		roleResults = statement.executeQuery();
    		
    		if (roleResults.next())
    		{
    			request.setAttribute("warning", 0);
    		}
    		else
    		{
    			statement = null;
    			statement = connection.prepareStatement(
    	    			"DELETE " +
    	    			"FROM ROLE " +
    	    			"WHERE ROLE_ID = ? ");
    	    	statement.setString(1, roleID);
    	    	statement.execute();
    		}
    	} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("delete role failed", e);
		} finally {
			closeStatement(statement);
			closeConnection(connection);
		}
        //Forward to the jsp page for rendering
        request.getRequestDispatcher("/Role/ListRole").forward(request, response);
    }
       
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}


}
